package cn.itsource.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.itsource.order.domain.OrderDTO;
import cn.itsource.order.domain.TOrderAddress;
import cn.itsource.order.domain.TOrderAdopt;
import cn.itsource.order.mapper.OrderAdoptMapper;
import cn.itsource.order.mapper.TOrderAddressMapper;
import cn.itsource.order.service.AlipayService;
import cn.itsource.order.service.OrderAdoptService;
import cn.itsource.pet.domain.Pet;
import cn.itsource.pet.mapper.PetMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
public class OrderAdoptServiceImpl implements OrderAdoptService {
    @Autowired
    OrderAdoptMapper orderAdoptMapper;
    //创建订单的业务逻辑
    @Autowired
    PetMapper petMapper;
    @Autowired
    TOrderAddressMapper tOrderAddressMapper;
    @Autowired
    AlipayService alipayService;
    @Transactional
    @Override
    public String createOrder(OrderDTO orderDTO) {
        //1.生成订单的地址信息
        TOrderAddress tOrderAddress = BeanUtil.copyProperties(orderDTO.getUserAddress(), TOrderAddress.class);
        tOrderAddress.setId(null);


        //2.生成订单信息
        TOrderAdopt tOrderAdopt = new TOrderAdopt();
        //这里设置订单的基础信息
        tOrderAdopt.init(orderDTO);
        //将获取到的OrderSn复制给订单地址表
        tOrderAddress.setOrderSn(tOrderAdopt.getOrderSn());
        //默认del
        tOrderAddress.setDel(true);
        tOrderAddressMapper.insertSelective(tOrderAddress);
        if(Objects.nonNull(orderDTO.getPetId())){
            //通过宠物id 获取对应的宠物店铺id
            Long petId = orderDTO.getPetId();
            Pet pet = petMapper.selectByPrimaryKey(petId);
            tOrderAdopt.setShopId(pet.getShopId());
        }
        tOrderAdopt.setAddressId(tOrderAddress.getId());
        orderAdoptMapper.insertSelective(tOrderAdopt);


        //3.调用支付宝,唤起支付宝的支付界面
       return alipayService.createPayUrl(orderDTO.getRealPayMoney().doubleValue(),orderDTO.getPayNote(),tOrderAdopt.getOrderSn());
    }

    @Override
    public TOrderAdopt findByOrderSn(String out_trade_no) {
        return orderAdoptMapper.findByOrderSn(out_trade_no);
    }

    @Override
    public void update(TOrderAdopt orderAdopt) {
        orderAdoptMapper.updateByPrimaryKeySelective(orderAdopt);
    }
}
